﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Data;
using System.Data.SqlClient;

using SIPO.Library;
using SIPO.Library.DomainObject.Administration.UserManagement;
using SIPO.Library.Enum;
using SIPO.Library.Interfaces;

namespace SIPO.Library.DataAccess.Administration.UserManagement
{
    public partial class recUserRepo : ISearchable<recUser>
    {

        public List<recUser> GetListEksternalUser(int pageSize, int currentPage, string sortName, string sortOrder, string parameters)
        {
            List<recUser> tt = new List<recUser>();
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    int startRow = ((currentPage - 1) * pageSize) + 1;
                    int endRow = (startRow + pageSize);
                   

                    StringBuilder sbQuery = new StringBuilder();
                    sbQuery.AppendFormat(" WITH result_set AS ");
                    sbQuery.AppendFormat(" ( ");
                    sbQuery.AppendFormat("    SELECT ");
                    sbQuery.AppendFormat("      ROW_NUMBER() OVER (ORDER BY {0} {1}) AS [row_number], ", sortName, sortOrder);
                    sbQuery.AppendFormat("      a.UserID, a.UserCode, a.UserName, a.Email, a.Password, a.IsActive,a.DebtorID,b.DebtorName, a.Mobile, a.CreatedBy, a.CreatedDate, a.UpdatedBy, a.UpdatedDate ");
                    sbQuery.AppendFormat("    FROM ");
                    sbQuery.AppendFormat("      [master].recUser a left join [master].recDebtor b on (a.DebtorID=b.DebtorID)");
                    sbQuery.AppendFormat("    {0}", parameters);
                    sbQuery.AppendFormat(" ) ");
                    sbQuery.AppendFormat(" SELECT * FROM result_set WHERE [row_number] BETWEEN {0} AND {1} ", startRow, endRow);

                    cmd.CommandText = sbQuery.ToString();
                    cmd.CommandType = CommandType.Text;
                    try
                    {
                        conn.Open();
                        using (SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
                        {
                            while (dr.Read())
                            {
                                
                                recUser t = new recUser();
                              
                                t.UserID = dr[recUser.Fields.UserID] == DBNull.Value ? 0 : int.Parse(dr[recUser.Fields.UserID].ToString());
                                t.UserName = dr[recUser.Fields.UserName] == DBNull.Value ? string.Empty : dr[recUser.Fields.UserName].ToString();
                                t.UserCode = dr[recUser.Fields.UserCode] == DBNull.Value ? string.Empty : dr[recUser.Fields.UserCode].ToString();
                                t.Email = dr[recUser.Fields.Email] == DBNull.Value ? string.Empty : dr[recUser.Fields.Email].ToString();
                                t.Password = dr[recUser.Fields.Password] == DBNull.Value ? string.Empty : dr[recUser.Fields.Password].ToString();
                                t.IsActive = dr[recUser.Fields.IsActive] == DBNull.Value ? (bool?)null : bool.Parse(dr[recUser.Fields.IsActive].ToString());
                                t.DebtorID = dr[recUser.Fields.DebtorID] == DBNull.Value ? 0 : int.Parse(dr[recUser.Fields.DebtorID].ToString());
                                t.DebtorName = dr[recUser.Fields.DebtorName] == DBNull.Value ? string.Empty : dr[recUser.Fields.DebtorName].ToString();
                                t.Mobile = dr[recUser.Fields.Mobile] == DBNull.Value ? string.Empty : dr[recUser.Fields.Mobile].ToString();
                                t.CreatedBy = dr[recUser.Fields.CreatedBy] == DBNull.Value ? string.Empty : dr[recUser.Fields.CreatedBy].ToString();
                                t.CreatedDate = dr[recUser.Fields.CreatedDate] == DBNull.Value ? (DateTime?)null : DateTime.Parse(dr[recUser.Fields.CreatedDate].ToString());
                                t.UpdatedBy = dr[recUser.Fields.UpdatedBy] == DBNull.Value ? string.Empty : dr[recUser.Fields.UpdatedBy].ToString();
                                t.UpdatedDate = dr[recUser.Fields.UpdatedDate] == DBNull.Value ? (DateTime?)null : DateTime.Parse(dr[recUser.Fields.UpdatedDate].ToString());
                                tt.Add(t);
                                t.Dispose();
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        throw (ex);
                    }
                    finally
                    {
                        if (conn.State == ConnectionState.Open) conn.Close();
                    }
                }
            }
            return tt;
        }
        public List<recUser> GetList(int pageSize, int currentPage, string sortName, string sortOrder, string parameters)
        {
            List<recUser> tt = new List<recUser>();
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    int startRow = ((currentPage - 1) * pageSize) + 1;
                    int endRow = (startRow + pageSize);

                    StringBuilder sbQuery = new StringBuilder();
                    if (pageSize == -1 && currentPage == -1 && parameters.Contains("where a.userid in")) // cek apakah dipanggil dari form debtorsector list
                    {
                        sbQuery.AppendFormat("    SELECT ");
                        sbQuery.AppendFormat("      a.UserID, a.UserCode, a.UserName, a.Email, a.Password, a.IsActive,a.DebtorID,b.DebtorName, a.Mobile, a.CreatedBy, a.CreatedDate, a.UpdatedBy, a.UpdatedDate ");
                        sbQuery.AppendFormat("    FROM ");
                        sbQuery.AppendFormat("      [master].recUser a left join [master].recDebtor b on (a.DebtorID=b.DebtorID)");
                        sbQuery.AppendFormat("    {0}", parameters);
                    }
                    else
                    {
                        sbQuery.AppendFormat(" WITH result_set AS ");
                        sbQuery.AppendFormat(" ( ");
                        sbQuery.AppendFormat("    SELECT ");
                        sbQuery.AppendFormat("      ROW_NUMBER() OVER (ORDER BY {0} {1}) AS [row_number], ", sortName, sortOrder);
                        sbQuery.AppendFormat("      a.UserID, a.UserCode, a.UserName, a.Email, a.Password, a.IsActive,a.DebtorID,b.DebtorName, a.Mobile, a.CreatedBy, a.CreatedDate, a.UpdatedBy, a.UpdatedDate ");
                        sbQuery.AppendFormat("    FROM ");
                        sbQuery.AppendFormat("      [master].recUser a left join [master].recDebtor b on (a.DebtorID=b.DebtorID)");
                        sbQuery.AppendFormat("    {0}", parameters);
                        sbQuery.AppendFormat(" ) ");
                        sbQuery.AppendFormat(" SELECT * FROM result_set WHERE [row_number] BETWEEN {0} AND {1} ", startRow, endRow);
                    }
                    cmd.CommandText = sbQuery.ToString();
                    cmd.CommandType = CommandType.Text;
                    try
                    {
                        conn.Open();
                        using (SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
                        {
                            while (dr.Read())
                            {

                                recUser t = new recUser();

                                t.UserID = dr[recUser.Fields.UserID] == DBNull.Value ? 0 : int.Parse(dr[recUser.Fields.UserID].ToString());
                                t.UserName = dr[recUser.Fields.UserName] == DBNull.Value ? string.Empty : dr[recUser.Fields.UserName].ToString();
                                t.UserCode = dr[recUser.Fields.UserCode] == DBNull.Value ? string.Empty : dr[recUser.Fields.UserCode].ToString();
                                t.Email = dr[recUser.Fields.Email] == DBNull.Value ? string.Empty : dr[recUser.Fields.Email].ToString();
                                t.Password = dr[recUser.Fields.Password] == DBNull.Value ? string.Empty : dr[recUser.Fields.Password].ToString();
                                t.IsActive = dr[recUser.Fields.IsActive] == DBNull.Value ? (bool?)null : bool.Parse(dr[recUser.Fields.IsActive].ToString());
                                t.DebtorID = dr[recUser.Fields.DebtorID] == DBNull.Value ? 0 : int.Parse(dr[recUser.Fields.DebtorID].ToString());
                                t.DebtorName = dr[recUser.Fields.DebtorName] == DBNull.Value ? string.Empty : dr[recUser.Fields.DebtorName].ToString();
                                t.Mobile = dr[recUser.Fields.Mobile] == DBNull.Value ? string.Empty : dr[recUser.Fields.Mobile].ToString();
                                t.CreatedBy = dr[recUser.Fields.CreatedBy] == DBNull.Value ? string.Empty : dr[recUser.Fields.CreatedBy].ToString();
                                t.CreatedDate = dr[recUser.Fields.CreatedDate] == DBNull.Value ? (DateTime?)null : DateTime.Parse(dr[recUser.Fields.CreatedDate].ToString());
                                t.UpdatedBy = dr[recUser.Fields.UpdatedBy] == DBNull.Value ? string.Empty : dr[recUser.Fields.UpdatedBy].ToString();
                                t.UpdatedDate = dr[recUser.Fields.UpdatedDate] == DBNull.Value ? (DateTime?)null : DateTime.Parse(dr[recUser.Fields.UpdatedDate].ToString());
                                tt.Add(t);
                                t.Dispose();
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        throw (ex);
                    }
                    finally
                    {
                        if (conn.State == ConnectionState.Open) conn.Close();
                    }
                }
            }
            return tt;
        }
        public List<recUser> GetListInternalUser(int pageSize, int currentPage, string sortName, string sortOrder, string parameters)
        {
            List<recUser> tt = new List<recUser>();
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    int startRow = ((currentPage - 1) * pageSize) + 1;
                    int endRow = (startRow + pageSize);
                  
                    StringBuilder sbQuery = new StringBuilder();
                    sbQuery.AppendFormat(" WITH result_set AS ");
                    sbQuery.AppendFormat(" ( ");
                    sbQuery.AppendFormat("    SELECT ");
                    sbQuery.AppendFormat("      ROW_NUMBER() OVER (ORDER BY {0} {1}) AS [row_number], ", sortName, sortOrder);
                    sbQuery.AppendFormat("      UserID, UserCode, UserName, Email, Password, IsActive,DebtorID, Mobile, CreatedBy, CreatedDate,UpdatedBy, UpdatedDate ");
                    sbQuery.AppendFormat("    FROM ");
                    sbQuery.AppendFormat("      [master].recUser");
                    sbQuery.AppendFormat("    {0}", parameters);
                    sbQuery.AppendFormat(" ) ");
                    sbQuery.AppendFormat(" SELECT * FROM result_set WHERE [row_number] BETWEEN {0} AND {1} ", startRow, endRow);

                    cmd.CommandText = sbQuery.ToString();
                    cmd.CommandType = CommandType.Text;
                    try
                    {
                        conn.Open();
                        using (SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
                        {
                            while (dr.Read())
                            {

                                recUser t = new recUser();

                                t.UserID = dr[recUser.Fields.UserID] == DBNull.Value ? 0 : int.Parse(dr[recUser.Fields.UserID].ToString());
                                t.UserName = dr[recUser.Fields.UserName] == DBNull.Value ? string.Empty : dr[recUser.Fields.UserName].ToString();
                                t.UserCode = dr[recUser.Fields.UserCode] == DBNull.Value ? string.Empty : dr[recUser.Fields.UserCode].ToString();
                                t.Email = dr[recUser.Fields.Email] == DBNull.Value ? string.Empty : dr[recUser.Fields.Email].ToString();
                                t.Password = dr[recUser.Fields.Password] == DBNull.Value ? string.Empty : dr[recUser.Fields.Password].ToString();
                                t.IsActive = dr[recUser.Fields.IsActive] == DBNull.Value ? (bool?)null : bool.Parse(dr[recUser.Fields.IsActive].ToString());
                                t.DebtorID = dr[recUser.Fields.DebtorID] == DBNull.Value ? 0 : int.Parse(dr[recUser.Fields.DebtorID].ToString());
                                  t.Mobile = dr[recUser.Fields.Mobile] == DBNull.Value ? string.Empty : dr[recUser.Fields.Mobile].ToString();
                                t.CreatedBy = dr[recUser.Fields.CreatedBy] == DBNull.Value ? string.Empty : dr[recUser.Fields.CreatedBy].ToString();
                                t.CreatedDate = dr[recUser.Fields.CreatedDate] == DBNull.Value ? (DateTime?)null : DateTime.Parse(dr[recUser.Fields.CreatedDate].ToString());
                                t.UpdatedBy = dr[recUser.Fields.UpdatedBy] == DBNull.Value ? string.Empty : dr[recUser.Fields.UpdatedBy].ToString();
                                t.UpdatedDate = dr[recUser.Fields.UpdatedDate] == DBNull.Value ? (DateTime?)null : DateTime.Parse(dr[recUser.Fields.UpdatedDate].ToString());
                                tt.Add(t);
                                t.Dispose();
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        throw (ex);
                    }
                    finally
                    {
                        if (conn.State == ConnectionState.Open) conn.Close();
                    }
                }
            }
            return tt;
        }


        public object SelectScalar(SQL.Function.Aggregate function, string column, string parameters)
        {
            object _result = null;
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    StringBuilder sbQuery = new StringBuilder();
                    switch (function)
                    {
                        case SQL.Function.Aggregate.Max:
                            sbQuery.AppendFormat("SELECT MAX({0}) FROM [master].recUser {1}", column, parameters);
                            break;
                        case SQL.Function.Aggregate.Min:
                            sbQuery.AppendFormat("SELECT MIN({0}) FROM [master].recUser {1}", column, parameters);
                            break;
                        case SQL.Function.Aggregate.Distinct:
                            sbQuery.AppendFormat("SELECT DISTINCT({0}) [master].FROM recUser {1}", column, parameters);
                            break;
                        case SQL.Function.Aggregate.Count:
                            sbQuery.AppendFormat("SELECT COUNT({0}) FROM [master].recUser {1}", column, parameters);
                            break;
                        case SQL.Function.Aggregate.Sum:
                            sbQuery.AppendFormat("SELECT SUM({0}) FROM [master].recUser {1}", column, parameters);
                            break;
                        case SQL.Function.Aggregate.Avg:
                            sbQuery.AppendFormat("SELECT AVG({0}) FROM [master].recUser {1}", column, parameters);
                            break;
                        default:
                            // do nothing 
                            break;
                    }

                    cmd.CommandText = sbQuery.ToString();
                    cmd.CommandType = CommandType.Text;
                    try
                    {
                        conn.Open();
                        _result = cmd.ExecuteScalar();
                    }
                    catch (Exception ex)
                    {
                        throw (ex);
                    }
                    finally
                    {
                        if (conn.State == ConnectionState.Open) conn.Close();
                    }
                }
            }
            return _result;
        }

        public object SelectScalarEksternal(SQL.Function.Aggregate function, string column, string parameters)
        {
            object _result = null;
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    StringBuilder sbQuery = new StringBuilder();
                    switch (function)
                    {
                        case SQL.Function.Aggregate.Max:
                            sbQuery.AppendFormat("SELECT MAX({0}) FROM [master].recUser a left join [master].recDebtor b on (a.DebtorID=b.DebtorID) {1}", column, parameters);
                            break;
                        case SQL.Function.Aggregate.Min:
                            sbQuery.AppendFormat("SELECT MIN({0}) FROM [master].recUser a left join [master].recDebtor b on (a.DebtorID=b.DebtorID) {1}", column, parameters);
                            break;
                        case SQL.Function.Aggregate.Distinct:
                            sbQuery.AppendFormat("SELECT DISTINCT({0}) [master].FROM [master].recUser a left join [master].recDebtor b on (a.DebtorID=b.DebtorID) {1}", column, parameters);
                            break;
                        case SQL.Function.Aggregate.Count:
                            sbQuery.AppendFormat("SELECT COUNT({0}) FROM [master].recUser a left join [master].recDebtor b on (a.DebtorID=b.DebtorID) {1}", column, parameters);
                            break;
                        case SQL.Function.Aggregate.Sum:
                            sbQuery.AppendFormat("SELECT SUM({0}) FROM [master].recUser a left join [master].recDebtor b on (a.DebtorID=b.DebtorID) {1}", column, parameters);
                            break;
                        case SQL.Function.Aggregate.Avg:
                            sbQuery.AppendFormat("SELECT AVG({0}) FROM [master].recUser a left join [master].recDebtor b on (a.DebtorID=b.DebtorID) {1}", column, parameters);
                            break;
                        default:
                            // do nothing 
                            break;
                    }

                    cmd.CommandText = sbQuery.ToString();
                    cmd.CommandType = CommandType.Text;
                    try
                    {
                        conn.Open();
                        _result = cmd.ExecuteScalar();
                    }
                    catch (Exception ex)
                    {
                        throw (ex);
                    }
                    finally
                    {
                        if (conn.State == ConnectionState.Open) conn.Close();
                    }
                }
            }
            return _result;
        }

        public bool ValidateUser(string usercode, string password, out recUser t)
        {
            bool result = false;
            t = null;

            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = "select UserID, UserCode, UserName, Email, Password, IsActive, DebtorID, Mobile, CreatedBy, CreatedDate, UpdatedBy, UpdatedDate, UserTypeID, IsForgotPass FROM [master].recUser where (lower(UserCode) = lower(@UserCode)) and (password = @password)";
                    cmd.CommandType = CommandType.Text;
                    cmd.Parameters.Add("@UserCode", SqlDbType.VarChar).Value = usercode;
                    cmd.Parameters.Add("@password", SqlDbType.VarChar).Value = password;

                    try
                    {
                        conn.Open();
                        using (SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
                        {
                            if (dr.HasRows)
                            {
                                result = true;
                                t = new recUser();
                                if (dr.Read())
                                {
                                    t.UserID = dr[recUser.Fields.UserID] == DBNull.Value ? 0 : int.Parse(dr[recUser.Fields.UserID].ToString());
                                    t.UserCode = dr[recUser.Fields.UserCode] == DBNull.Value ? string.Empty : dr[recUser.Fields.UserCode].ToString();
                                    t.UserName = dr[recUser.Fields.UserName] == DBNull.Value ? string.Empty : dr[recUser.Fields.UserName].ToString();
                                    t.Email = dr[recUser.Fields.Email] == DBNull.Value ? string.Empty : dr[recUser.Fields.Email].ToString();
                                    t.Password = dr[recUser.Fields.Password] == DBNull.Value ? string.Empty : dr[recUser.Fields.Password].ToString();
                                    t.IsActive = dr[recUser.Fields.IsActive] == DBNull.Value ? (bool?)null : bool.Parse(dr[recUser.Fields.IsActive].ToString());
                                    t.DebtorID = dr[recUser.Fields.DebtorID] == DBNull.Value ? (int?)null : int.Parse(dr[recUser.Fields.DebtorID].ToString()); t.Mobile = dr[recUser.Fields.Mobile] == DBNull.Value ? string.Empty : dr[recUser.Fields.Mobile].ToString();
                                    t.CreatedBy = dr[recUser.Fields.CreatedBy] == DBNull.Value ? string.Empty : dr[recUser.Fields.CreatedBy].ToString();
                                    t.CreatedDate = dr[recUser.Fields.CreatedDate] == DBNull.Value ? (DateTime?)null : DateTime.Parse(dr[recUser.Fields.CreatedDate].ToString());
                                    t.UpdatedBy = dr[recUser.Fields.UpdatedBy] == DBNull.Value ? string.Empty : dr[recUser.Fields.UpdatedBy].ToString();
                                    t.UpdatedDate = dr[recUser.Fields.UpdatedDate] == DBNull.Value ? (DateTime?)null : DateTime.Parse(dr[recUser.Fields.UpdatedDate].ToString());
                                    t.UserTypeID = dr[recUser.Fields.UserTypeID] == DBNull.Value ? (int?)null : int.Parse(dr[recUser.Fields.UserTypeID].ToString());
                                    t.IsForgotPass = dr[recUser.Fields.IsForgotPass] == DBNull.Value ? false : bool.Parse(dr[recUser.Fields.IsForgotPass].ToString());
                                }
                            }
                            else
                                result = false;
                        }
                    }
                    catch (Exception ex)
                    {
                        throw (ex);
                    }
                    finally
                    {
                        if (conn.State == ConnectionState.Open) conn.Close();
                    }
                }
            }
            return result;
        }

        public bool Update(int UserID, string password, string auditUser)
        {
            int result = 0;
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = "UPDATE [master].recUser SET UpdatedDate = GetDate(), UpdatedBy = @auditUser, Password = @password WHERE UserID = @UserID";
                    cmd.CommandType = CommandType.Text;
                    cmd.Parameters.Add("@UserID", SqlDbType.Int).Value = UserID;
                    cmd.Parameters.Add("@password", SqlDbType.VarChar).Value = password;
                    cmd.Parameters.Add("@auditUser", SqlDbType.VarChar).Value = auditUser;

                    try
                    {
                        conn.Open();
                        result = cmd.ExecuteNonQuery();
                    }
                    catch (Exception ex)
                    {
                        throw (ex);
                    }
                    finally
                    {
                        if (conn.State == ConnectionState.Open) conn.Close();
                    }
                }
            }
            return (result > 0);
        }
        public bool Update(int UserID, string password, string auditUser,bool IsForgotPass)
        {
            int result = 0;
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = "UPDATE [master].recUser SET UpdatedDate = GetDate(), UpdatedBy = @auditUser, Password = @password, IsForgotPass = @isforgot WHERE UserID = @UserID";
                    cmd.CommandType = CommandType.Text;
                    cmd.Parameters.Add("@UserID", SqlDbType.Int).Value = UserID;
                    cmd.Parameters.Add("@password", SqlDbType.VarChar).Value = password;
                    cmd.Parameters.Add("@auditUser", SqlDbType.VarChar).Value = auditUser;
                    cmd.Parameters.Add("@isforgot", SqlDbType.VarChar).Value = IsForgotPass;

                    try
                    {
                        conn.Open();
                        result = cmd.ExecuteNonQuery();
                    }
                    catch (Exception ex)
                    {
                        throw (ex);
                    }
                    finally
                    {
                        if (conn.State == ConnectionState.Open) conn.Close();
                    }
                }
            }
            return (result > 0);
        }

        public recUser GetByUserCode(string usercode)
        {
            recUser t = null;
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = "SELECT UserID, UserCode, UserName,UserTypeID, Email, Password, IsActive, DebtorID, Mobile, CreatedBy, CreatedDate, UpdatedBy, UpdatedDate FROM master.recUser WHERE (lower(UserCode) = lower(@UserCode))";
                    cmd.CommandType = CommandType.Text;
                    cmd.Parameters.Add("@UserCode", SqlDbType.VarChar).Value = usercode;
                    try
                    {
                        conn.Open();
                        using (SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
                        {
                            while (dr.Read())
                            {
                                t = new recUser();
                                t.UserID = dr[recUser.Fields.UserID] == DBNull.Value ? 0 : int.Parse(dr[recUser.Fields.UserID].ToString());
                                t.UserCode = dr[recUser.Fields.UserCode] == DBNull.Value ? string.Empty : dr[recUser.Fields.UserCode].ToString();
                                t.UserName = dr[recUser.Fields.UserName] == DBNull.Value ? string.Empty : dr[recUser.Fields.UserName].ToString();
                                t.UserTypeID = dr[recUser.Fields.UserTypeID] == DBNull.Value ? 0 : int.Parse(dr[recUser.Fields.UserTypeID].ToString());
                                t.Email = dr[recUser.Fields.Email] == DBNull.Value ? string.Empty : dr[recUser.Fields.Email].ToString();
                                t.Password = dr[recUser.Fields.Password] == DBNull.Value ? string.Empty : dr[recUser.Fields.Password].ToString();
                                t.IsActive = dr[recUser.Fields.IsActive] == DBNull.Value ? (bool?)null : bool.Parse(dr[recUser.Fields.IsActive].ToString());
                                t.DebtorID = dr[recUser.Fields.DebtorID] == DBNull.Value ? (int?)null : int.Parse(dr[recUser.Fields.DebtorID].ToString());
                                t.Mobile = dr[recUser.Fields.Mobile] == DBNull.Value ? string.Empty : dr[recUser.Fields.Mobile].ToString();
                                t.CreatedBy = dr[recUser.Fields.CreatedBy] == DBNull.Value ? string.Empty : dr[recUser.Fields.CreatedBy].ToString();
                                t.CreatedDate = dr[recUser.Fields.CreatedDate] == DBNull.Value ? (DateTime?)null : DateTime.Parse(dr[recUser.Fields.CreatedDate].ToString());
                                t.UpdatedBy = dr[recUser.Fields.UpdatedBy] == DBNull.Value ? string.Empty : dr[recUser.Fields.UpdatedBy].ToString();
                                t.UpdatedDate = dr[recUser.Fields.UpdatedDate] == DBNull.Value ? (DateTime?)null : DateTime.Parse(dr[recUser.Fields.UpdatedDate].ToString());
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        throw (ex);
                    }
                    finally
                    {
                        if (conn.State == ConnectionState.Open) conn.Close();
                    }
                }
            }
            return t;
        }

        public int validasiEmail(string email)
        {
            
            int jml = -1;

            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = "select count(Email) as jmlEmail from master.recUser where Email = @Email";
                    cmd.CommandType = CommandType.Text;
                    cmd.Parameters.Add("@Email", SqlDbType.VarChar).Value = email;
                    
                    try
                    {
                        conn.Open();
                        using (SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
                        {
                            if (dr.Read())
                            {
                                //jml = int.Parse(dr["jmlEmail"].ToString());
                                //jml = dr.GetInt32(0);
                                jml = Convert.ToInt32(dr["jmlEmail"]);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        throw (ex);
                    }
                    finally
                    {
                        if (conn.State == ConnectionState.Open) conn.Close();
                    }
                }
            }
            
            return jml;
        }

        public int validasiEmailbyUser(string email,string usercode,string pass)
        {
           
            int status = -1;
            try // cek apakah user terdaftar
            {
                recUser user = GetByUserCode(usercode);
                string userid = user.UserCode;
                status = 1; // jika terdaftar status 1
            }
            catch
            {
                //do nothing
            }

            int jml = -1;
            int cekEmail =-1;

            if (status == -1) // jika tidak terdaftar
            {
                cekEmail = validasiEmail(email);
                if (cekEmail > 0)
                {
                    jml = 1;
                }
            }
            else if (status ==1) // jika terdaftar, cek apakah email cocok
            {
                using (SqlConnection conn = new SqlConnection(connectionString))
                {
                    using (SqlCommand cmd = conn.CreateCommand())
                    {
                        cmd.CommandText = "select count(Email) as jmlEmail from master.recUser where Email = @Email and (usercode = @Usercode and password = @Password)";
                        cmd.CommandType = CommandType.Text;
                        cmd.Parameters.Add("@Email", SqlDbType.VarChar).Value = email;
                        cmd.Parameters.Add("@Usercode", SqlDbType.VarChar).Value = usercode;
                        cmd.Parameters.Add("@Password", SqlDbType.VarChar).Value = pass;
                        try
                        {
                            conn.Open();
                            using (SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
                            {
                                if (dr.Read())
                                {
                                    //jml = int.Parse(dr["jmlEmail"].ToString());
                                    //jml = dr.GetInt32(0);
                                    jml = Convert.ToInt32(dr["jmlEmail"]);
                                }
                               }
                            if (jml > 0)
                            {
                                jml = 0;
                            }
                            else
                            {
                                jml = 1;
                            }
                        }
                        catch (Exception ex)
                        {
                            throw (ex);
                        }
                        finally
                        {
                            if (conn.State == ConnectionState.Open) conn.Close();
                        }
                    }
                }
            }

            return jml;
        }

        public recUser GetByEmail(string email)
        {
            recUser t = null;
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = "SELECT UserID, UserCode, UserName,UserTypeID, email,Password, IsActive, DebtorID, Mobile, CreatedBy, CreatedDate, UpdatedBy, UpdatedDate FROM master.recUser WHERE lower(email) = @Email";
                    cmd.CommandType = CommandType.Text;
                    cmd.Parameters.Add("@Email", SqlDbType.VarChar).Value  = email.ToLower();
                    try
                    {
                        conn.Open();
                        using (SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
                        {
                            while (dr.Read())
                            {
                                t = new recUser();
                                t.UserID = dr[recUser.Fields.UserID] == DBNull.Value ? 0 : int.Parse(dr[recUser.Fields.UserID].ToString());
                                t.UserCode = dr[recUser.Fields.UserCode] == DBNull.Value ? string.Empty : dr[recUser.Fields.UserCode].ToString();
                                t.UserName = dr[recUser.Fields.UserName] == DBNull.Value ? string.Empty : dr[recUser.Fields.UserName].ToString();
                                t.UserTypeID = dr[recUser.Fields.UserTypeID] == DBNull.Value ? 0 : int.Parse(dr[recUser.Fields.UserTypeID].ToString());
                                t.Email = dr[recUser.Fields.Email] == DBNull.Value ? string.Empty : dr[recUser.Fields.Email].ToString();
                                t.Password = dr[recUser.Fields.Password] == DBNull.Value ? string.Empty : dr[recUser.Fields.Password].ToString();
                                t.IsActive = dr[recUser.Fields.IsActive] == DBNull.Value ? (bool?)null : bool.Parse(dr[recUser.Fields.IsActive].ToString());
                                t.DebtorID = dr[recUser.Fields.DebtorID] == DBNull.Value ? (int?)null : int.Parse(dr[recUser.Fields.DebtorID].ToString());
                                t.Mobile = dr[recUser.Fields.Mobile] == DBNull.Value ? string.Empty : dr[recUser.Fields.Mobile].ToString();
                                t.CreatedBy = dr[recUser.Fields.CreatedBy] == DBNull.Value ? string.Empty : dr[recUser.Fields.CreatedBy].ToString();
                                t.CreatedDate = dr[recUser.Fields.CreatedDate] == DBNull.Value ? (DateTime?)null : DateTime.Parse(dr[recUser.Fields.CreatedDate].ToString());
                                t.UpdatedBy = dr[recUser.Fields.UpdatedBy] == DBNull.Value ? string.Empty : dr[recUser.Fields.UpdatedBy].ToString();
                                t.UpdatedDate = dr[recUser.Fields.UpdatedDate] == DBNull.Value ? (DateTime?)null : DateTime.Parse(dr[recUser.Fields.UpdatedDate].ToString());
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        throw (ex);
                    }
                    finally
                    {
                        if (conn.State == ConnectionState.Open) conn.Close();
                    }
                }
            }
            return t;
        }

        public bool CheckDataByUserCode(string code)
        {
            bool _result = false;
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    StringBuilder sbQuery = new StringBuilder();

                    sbQuery.AppendFormat("SELECT COUNT(LOWER(UserCode)) UserCode FROM master.recUser WHERE LOWER(UserCode)=@UserCode");
                    cmd.Parameters.Add("@UserCode", SqlDbType.VarChar).Value = code.ToLower();

                    cmd.CommandText = sbQuery.ToString();
                    cmd.CommandType = CommandType.Text;

                    try
                    {
                        conn.Open();

                        var objId = cmd.ExecuteScalar();
                        objId = objId == DBNull.Value ? 0 : int.Parse(objId.ToString());

                        _result = int.Parse(objId.ToString()) == 0 ? false : true;

                    }
                    catch (Exception ex)
                    {
                        throw (ex);
                    }
                    finally
                    {
                        if (conn.State == ConnectionState.Open) conn.Close();
                    }
                }
            }
            return _result;
        }
        
        public bool CheckIsInternalUser(int userid)
        {

            SqlConnection conn = new SqlConnection(connectionString);
            SqlCommand GetDebtorID = new SqlCommand("select debtorid from master.recuser where userid=" + userid, conn);
            int Debtorid = 0;
            try
            {
                conn.Open();
                Debtorid = Convert.ToInt32(GetDebtorID.ExecuteScalar());
                conn.Close();
            }
            catch {   
            //do nothing
            }
            if( Debtorid == 0)
                return true;
            else
            return false;
            
        }

        public bool SetActivation(recUser domain)
        {
            int result = 0;
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = "UPDATE master.recUser SET IsActive = @IsActive, UpdatedDate = @UpdatedDate, UpdatedBy = @UpdatedBy WHERE DebtorID = @DebtorID";
                    cmd.CommandType = CommandType.Text;
                    cmd.Parameters.Add("@DebtorID", SqlDbType.Int).Value = domain.DebtorID;
                    cmd.Parameters.Add("@IsActive", SqlDbType.Bit).Value = domain.IsActive;
                    cmd.Parameters.Add("@UpdatedDate", SqlDbType.DateTime).Value = (object)domain.UpdatedDate ?? DBNull.Value;
                    cmd.Parameters.Add("@UpdatedBy", SqlDbType.VarChar).Value = (object)domain.UpdatedBy ?? DBNull.Value;

                    try
                    {
                        conn.Open();
                        result = cmd.ExecuteNonQuery();
                    }
                    catch (Exception ex)
                    {
                        throw (ex);
                    }
                    finally
                    {
                        if (conn.State == ConnectionState.Open) conn.Close();
                    }
                }
            }
            return (result > 0);
        }  

    }

}
